package cn.aspect;

import cn.entity.SysLog;
import cn.entity.SysUser;
import cn.service.SysLogService;
import cn.utils.IPUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 日志切面类，用于进行日志的aop切面处理：
 * 1.正常日志
 * 2.异常日志
 */
@Aspect
@Component
public class LogAspect {


    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private HttpServletRequest request;


    @Pointcut("within((cn.service.impl.*Impl))")
    public void pointcut(){};




    /**
     * 正常日志
     * @param joinPoint   连接点对象
     */
    @AfterReturning(pointcut = "pointcut()")
    public void afterReturning(JoinPoint joinPoint){
        String className = joinPoint.getTarget().getClass().getSimpleName();
        if(!"SysLogServiceImpl".equals(className)) {
            insertLog(joinPoint, null);
        }
    }


    //异常日志
    @AfterThrowing(pointcut = "pointcut()",throwing = "e")
    public void throwing(JoinPoint joinPoint,Exception e){
        insertLog(joinPoint,e);
    }

    private void insertLog(JoinPoint joinPoint, Exception e) {
        SysLog sysLog = new SysLog();
        //request有关处理
        if(request!=null){
            SysUser loginUser = (SysUser) request.getSession().getAttribute("user");
            if (loginUser!=null) {
                sysLog.setCreateBy(loginUser != null ? loginUser.getName() : "");
                sysLog.setRemoteAddr(IPUtils.getClientAddress(request));
                sysLog.setUserAgent(request.getHeader("User-Agent"));
                sysLog.setRequestUri(request.getRequestURI());
                sysLog.setMethod(request.getMethod());
                //异常信息
                sysLog.setType(e==null?"1":"2");
                sysLog.setException(e==null?"无":e.toString());

                //处理方法参数
                Object[] args = joinPoint.getArgs();

                //[参数1,类型:Integer,值:1][参数2,类型:Integer,值:5][参数3,类型:LinkedHashMap,值:{status=}]
                if(args!=null&args.length>0){
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < args.length; i++) {
                        sb.append("[参数").append(i+1).append(",类型:").append(args[i].getClass().getSimpleName())
                                .append(",值:").append(args[i]).append("]");
                    }
                }
                sysLog.setCreateDate(new Date());
                sysLogService.insertSelective(sysLog);
            }
        }

    }



}
